// 1. React核心库
import React, { useEffect, useState } from 'react';

// 2. UI组件库 - 按字母顺序
import { Button, Form, Input, Select, Space, message } from 'antd';

// 4. 专业组件库
import { ProForm, ProFormText, ProFormSelect, ProFormTextArea } from '@ant-design/pro-components';

// 5. 工具库
 

// 7. 项目内部模块
import { apiClients } from '@/services/apiClient';
import { autoLoginInDev } from '@/utils/autoLogin';

// 8. 生成的类型定义 (必须使用，禁止手工定义)
import type { AIConversation, AIModel, AIRole } from '@/services/generated';

interface ConversationFormProps {
  initialValues?: AIConversation | null;
  onSuccess: () => void;
  onCancel: () => void;
}

const ConversationForm: React.FC<ConversationFormProps> = ({
  initialValues,
  onSuccess,
  onCancel,
}) => {
  const [form] = Form.useForm();
  const [models, setModels] = useState<AIModel[]>([]);
  const [roles, setRoles] = useState<AIRole[]>([]);
  const isEdit = !!initialValues?.id;

  // 获取AI模型列表
  const fetchModels = 
    async () => {
      await autoLoginInDev();
      const response = await apiClients.aiChat.aiChatModelsList({});
      setModels(response.data?.items || []);
    }

  // 获取AI角色列表
  const fetchRoles = 
    async () => {
      await autoLoginInDev();
      const response = await apiClients.aiChat.aiChatRolesList({});
      setRoles(response.data?.items || []);
    }

  // 创建对话
  const createConversation = 
    async (values: any) => {
      await autoLoginInDev();
      await apiClients.aiChat.aiChatConversationsCreate({
        aIConversationRequest: values,
      });
    } 

  // 更新对话
  const updateConversation = 
    async (values: any) => {
      await autoLoginInDev();
      await apiClients.aiChat.aiChatConversationsUpdate({
        id: String(initialValues!.id!),
        aIConversationRequest: values,
      });
    } 

  // 表单提交
  const handleSubmit = async (values: any) => {
    if (isEdit) {
      await updateConversation(values);
    } else {
      await createConversation(values);
    }
  };

  // 初始化数据
  useEffect(() => {
    fetchModels();
    fetchRoles();
    
    if (initialValues) {
      form.setFieldsValue(initialValues);
    }
  }, [initialValues, form, fetchModels, fetchRoles]);

  return (
    <ProForm
      form={form}
      layout="vertical"
      onFinish={handleSubmit}
      submitter={{
        render: (_, dom) => (
          <Space style={{ width: '100%', justifyContent: 'flex-end' }}>
            <Button onClick={onCancel}>取消</Button>
            <Button
              type="primary"
         
              onClick={() => form.submit()}
            >
              {isEdit ? '更新' : '创建'}
            </Button>
          </Space>
        ),
      }}
    >
      <ProFormText
        name="title"
        label="对话标题"
        placeholder="请输入对话标题"
        rules={[
          { required: true, message: '请输入对话标题' },
          { max: 200, message: '标题长度不能超过200个字符' },
        ]}
      />

      <ProFormSelect
        name="ai_model"
        label="AI模型"
        placeholder="请选择AI模型"
        options={models.map(model => ({
          label: `${model.name} (${model.model_code})`,
          value: model.id,
        }))}
        rules={[{ required: true, message: '请选择AI模型' }]}
      />

      <ProFormSelect
        name="ai_role"
        label="AI角色"
        placeholder="请选择AI角色（可选）"
        options={roles.map(role => ({
          label: role.name,
          value: role.id,
        }))}
      />

      <ProFormSelect
        name="status"
        label="状态"
        placeholder="请选择状态"
        options={[
          { label: '活跃', value: 'active' },
          { label: '已归档', value: 'archived' },
        ]}
        initialValue="active"
        rules={[{ required: true, message: '请选择状态' }]}
      />
    </ProForm>
  );
};

export default ConversationForm;
